//
//  BQLocationManager.m
//  honeycomb
//
//  Created by 陈 宁权 on 16/7/5.
//  Copyright © 2016年 www.bqjr.cn. All rights reserved.
//

#import "BQLocationManager.h"

@interface BQLocationManager()<CLLocationManagerDelegate>

@end

@implementation BQLocationManager

+ (instancetype)sharedManager
{
    static BQLocationManager *instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[BQLocationManager alloc] init];
    });
    
    return instance;
}

- (instancetype)init
{
    self = [super init];
    if ( self )
    {
        self.minSpeed = 3;
        self.minFilter = 500;
        self.minInteval = 200;
        self.delegate = self;
        self.distanceFilter  = self.minFilter;
        self.desiredAccuracy = kCLLocationAccuracyBest;
        self.pausesLocationUpdatesAutomatically = NO;
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
        {
            [self requestWhenInUseAuthorization];  //调用了这句,就会弹出允许框了.
//            [self requestAlwaysAuthorization];
        }
    }
    return self;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = locations[0];
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark *placemark in placemarks) {
            
            self.province = placemark.administrativeArea;
            self.city = placemark.locality;
            self.position = [NSString stringWithFormat:@"%@%@%@%@%@",placemark.country,placemark.administrativeArea,placemark.locality,placemark.subLocality,placemark.thoroughfare];
        }
    }];

    //根据实际情况来调整触发范围
    [self adjustDistanceFilter:location];
    //上传数据
    [self uploadLocation:location];
    
}


- (void)uploadLocation:(CLLocation *)location
{
    BOOL isuploadLocation = [self compareLastDateWithCurrentDate];
    if (isuploadLocation) {
        NSInteger timeInterval = [location.timestamp timeIntervalSince1970];
        NSString *lastdateStr = [NSString stringWithFormat:@"%ld",(long)timeInterval];
        [[NSUserDefaults standardUserDefaults] setObject:lastdateStr forKey:@"locationLastDate"];
        
        //停止定位
        [[BQLocationManager sharedManager] stopUpdatingLocation];
        //创建一个串行队列
        dispatch_queue_t queue = dispatch_queue_create("uploadLocationqueue", DISPATCH_QUEUE_SERIAL);
        //异步执行
        dispatch_async(queue, ^{
            //上传经纬度
            
        });
    }
}

- (BOOL)compareLastDateWithCurrentDate
{
    NSDate *date = [NSDate date];
    NSInteger currentTimeInterval = [date timeIntervalSince1970];
    
    NSInteger lastTimeInterval = [[[NSUserDefaults standardUserDefaults] objectForKey:@"locationLastDate"] integerValue];
    if (!(lastTimeInterval > 0)) {
        return YES;
    }
    NSInteger time = currentTimeInterval - lastTimeInterval;
    if (time > 10) {
        return YES;
    }
    return NO;
}

-(void)mylog:(NSString*)logKey andValue:(NSString *)location
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectroy = [paths objectAtIndex:0];
    NSString *filename =@"test.plist";
    NSString *filePath = [documentsDirectroy stringByAppendingPathComponent:filename];
    //    NSLog(@"filePath:%@",filePath);
    NSFileManager *file =  [NSFileManager defaultManager];
    NSMutableDictionary *dic;
    if ([file fileExistsAtPath:filePath]) {
        dic = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    }else{
        dic = [[NSMutableDictionary alloc] init];
    }
    [dic setValue:location  forKey:logKey];
    [dic writeToFile:filePath atomically:YES];
}

/**
 *  规则: 如果速度小于minSpeed m/s 则把触发范围设定为50m
 *  否则将触发范围设定为minSpeed*minInteval
 *  此时若速度变化超过10% 则更新当前的触发范围(这里限制是因为不能不停的设置distanceFilter,
 *  否则uploadLocation会不停被触发)
 */
- (void)adjustDistanceFilter:(CLLocation*)location
{
    //        NSLog(@"adjust:%f",location.speed);
    
    if ( location.speed < self.minSpeed )
    {
        if ( fabs(self.distanceFilter-self.minFilter) > 0.1f )
        {
            self.distanceFilter = self.minFilter;
        }
    }
    else
    {
        CGFloat lastSpeed = self.distanceFilter/self.minInteval;
        
        if ( (fabs(lastSpeed-location.speed)/lastSpeed > 0.1f) || (lastSpeed < 0) )
        {
            CGFloat newSpeed  = (int)(location.speed+0.5f);
            CGFloat newFilter = newSpeed*self.minInteval;
            
            self.distanceFilter = newFilter;
        }
    }
}

- (NSString *)getPositionWithLocation:(CLLocation *)location
{
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark *placemark in placemarks) {
            self.addressName = placemark.name;
        }
    }];
    
    return self.addressName;
}

- (BOOL)haveLocationAuth
{
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
        //定位功能可用
        return YES;
    }else {
        //定位不能用
        return NO;
    }
}

@end
